package com.ten.system.service.impl;

import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ten.common.core.entity.AclPermission;
import com.ten.common.core.entity.AclRole;
import com.ten.common.core.entity.AclRolePermission;
import com.ten.security.utils.TokenToAll;
import com.ten.system.dao.AclPermissionDao;
import com.ten.system.service.AclPermissionService;
import com.ten.common.core.vo.Result;
import com.ten.system.service.AclRolePermissionService;
import com.ten.system.vo.FenPermissionVo;
import com.ten.system.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sun.dc.path.PathError;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/12/1 22:28
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class AclPermissionServiceImpl implements AclPermissionService {

    @Autowired(required = false)
    private AclPermissionDao aclPermissionDao;

    @Autowired(required = false)
    private AclRolePermissionService rolePermissionService;
    @Override
    public Result findByUserId(String userid) {
        List<AclPermission> aclPermissions = aclPermissionDao.selectByUserid(userid);
        return new Result<List<AclPermission>>(2000,"查询成功",aclPermissions);
    }

    @Override
    public Result<List<AclPermission>> findByUsername() {
    //1.获取登陆用户的用户名
        String username = TokenToAll.ToName();
    //2.调用dao中根据用户名查询该用户具有的菜单。
        List<AclPermission> permissions = aclPermissionDao.selectByUsername(username);
    //3.获取菜单目录
        //3.1.查询一级菜单
        List<AclPermission> first = new ArrayList<>();
        for (AclPermission permission : permissions) {
            if (permission.getPid().equals("1")){
                first.add(permission);
            }
        }
        //3.2.查询一级菜单下的子菜单
        for (AclPermission permission : first) {
            permission.setChildren(findChildren(permissions,permission.getId()));
        }
        return new Result<>(2000,"查询左侧菜单成功",first);
    }

    @Override
    public Result<Map<String, Object>> findAll(String roleId) {
        //获取所有权限
        List<AclPermission> permissions = aclPermissionDao.selectList(null);
        //1.得到一级菜单
        List<AclPermission> first=new ArrayList<>();
        for(AclPermission permission:permissions){
            if(permission.getPid().equals("1")){
                first.add(permission);
            }
        }
        //2.设置一级菜单的相应子菜单
        for(AclPermission p:first){
            p.setChildren(findChildren(permissions,p.getId()));
        }

        //获取当前角色具有的权限id
        List<String> perIds=aclPermissionDao.selectByRoleId(roleId);


        Map<String,Object> map=new HashMap<>();
        map.put("allPermissions",first);
        map.put("checkItems",perIds);

        return new Result<>(2000,"查询成功",map);
    }

    @Override
    @Transactional
    public Result confirmFenPermission(FenPermissionVo fenPermissionVo) {
        //根据角色id删除原来的具有的权限id
        UpdateWrapper<AclRolePermission> wrapper=new UpdateWrapper<>();
        wrapper.eq("role_id",fenPermissionVo.getRoleId());
        rolePermissionService.remove(wrapper);

        //批量添加角色具有的权限
        List<AclRolePermission> list=new ArrayList<>();
        for (String permissionId:fenPermissionVo.getPermissionIds()){
            AclRolePermission aclRolePermission = new AclRolePermission();
            aclRolePermission.setIsDeleted(0);
            aclRolePermission.setGmtCreate(LocalDateTime.now());
            aclRolePermission.setGmtModified(LocalDateTime.now());
            aclRolePermission.setPermissionId(permissionId);
            aclRolePermission.setRoleId(fenPermissionVo.getRoleId());
            list.add(aclRolePermission);
        }
        rolePermissionService.saveBatch(list);

        return new Result(2000,"分配权限成功");
    }

    @Override
    public Result findAllByPage(PermissionVo permissionVo, Integer currentPage, Integer pageSize) {
        //创建分页工具对象
        IPage<AclPermission> page = new Page<>(currentPage,pageSize);
        //条件查询对象
        QueryWrapper<AclPermission> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(permissionVo.getName())){
            wrapper.like("name",permissionVo.getName());
        }
        //获取所有菜单
        List<AclPermission> permissions = aclPermissionDao.selectList(wrapper);
        //1.得到一级菜单
        wrapper.eq("pid","1");
        IPage<AclPermission> page1 = aclPermissionDao.selectPage(page,wrapper);
        List<AclPermission> first = page1.getRecords();
        //2.设置一级菜单的相应子菜单
        for(AclPermission p:first){
            p.setTypeName("菜单");
            p.setChildren(findChildrens(permissions,p.getId()));
        }
        if(first!=null){
            return new Result<>(2000,"查询成功",page1.setRecords(first));
        }
        return new Result<>(4000,"查询失败");
    }

    //递归获取全部菜单
    private List<AclPermission> findChildrens(List<AclPermission> all,String fatherId){
        List<AclPermission> seconds = new ArrayList<>();
        for (AclPermission permission : all) {
            if (permission.getPid().equals(fatherId)){
                if (permission.getType()==1){
                    permission.setTypeName("目录");
                }else {
                    permission.setTypeName("按钮");
                }
                seconds.add(permission);
            }
        }
        for (AclPermission permission : seconds) {
            permission.setChildren(findChildren(all,permission.getId()));
        }
        return seconds;
    }
    //递归获取权限子菜单
    private List<AclPermission> findChildren(List<AclPermission> all,String fatherId){
        List<AclPermission> seconds = new ArrayList<>();
        for (AclPermission permission : all) {
            if (permission.getPid().equals(fatherId)){
                seconds.add(permission);
            }
        }
        for (AclPermission permission : seconds) {
            permission.setChildren(findChildren(seconds,permission.getId()));
        }
        return seconds;
    }
    @Override
    public Result insert(AclPermission aclPermission) {
        aclPermission.setGmtCreate(LocalDateTime.now());
        aclPermission.setGmtModified(LocalDateTime.now());
        int insert = aclPermissionDao.insert(aclPermission);
        if (insert==1){
            return new Result(2000,"添加成功!");
        }
        return new Result(4000,"添加失败!");
    }

    @Override
    @Transactional
    public Result deleteByIds(List ids) {
        int i = aclPermissionDao.deleteBatchIds(ids);
        if (i>=1){
            return new Result(2000,"删除成功!");
        }
        return new Result(4000,"删除失败!");
    }

    @Override
    @Transactional
    public Result update(AclPermission aclPermission) {
        aclPermission.setGmtModified(LocalDateTime.now());
        int i = aclPermissionDao.updateById(aclPermission);
        if (i==1){
            return new Result(2000,"修改成功!");
        }
        return new Result(4000,"修改失败!");
    }
}
